package com.zh.yida.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.yida.common.BusinessException;
import com.zh.yida.common.R;
import com.zh.yida.dto.DishDto;
import com.zh.yida.entity.Category;
import com.zh.yida.entity.Dish;
import com.zh.yida.entity.DishFlavor;
import com.zh.yida.entity.Setmeal;
import com.zh.yida.service.CategoryService;
import com.zh.yida.service.DishFlavorService;
import com.zh.yida.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveDishWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 页面分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> selectPage(int page, int pageSize, String name) {
        Page dishPage = new Page<Dish>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<Dish>();
        lqw.eq(name != null, Dish::getName, name);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
        dishService.page(dishPage, lqw);
        Page dishDtoPage = new Page<DishDto>();
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<DishDto> dishDtoList = new LinkedList<DishDto>();
        List<Dish> dishList = dishPage.getRecords();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            dishDtoList.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品和口味，回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> selectOne(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品和口味
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateishWithFlavor(dishDto);

        //移除所有的key
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //移除具体的key
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return  R.success("修改成功");
    }

    /**
     * 查询单个套餐的菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        List<Dish> dishList = dishService.list(lqw);
        dishDtos = new LinkedList<>();
        for (Dish dish1 : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId, dish1.getId());
            dishDto.setFlavors(dishFlavorService.list(lqw1));
            dishDtos.add(dishDto);
        }
        redisTemplate.opsForValue().set(key, dishDtos, 30, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

    /**
     * 修改套餐售卖状况，0：禁用， 1：启用
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, long[] ids) {
        if (ids == null) {
            throw new BusinessException("请选择要修改的套餐");
        } else {
            for (long id : ids) {
                Dish dish = dishService.getById(id);
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("修改成功");
    }
}